package com.zhongan.gateway.common.utils;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;

import com.zhongan.gateway.common.enums.GatewayErrorCodeEnum;
import com.zhongan.gateway.common.exception.GatewayException;

/**
 * 类EmptyCheckUtil.java的实现描述：非空校验类
 *
 * @author CHENQIMING 2016
 */
public class EmptyCheckUtil {

    /**
     * 非空校验
     * 
     * @param bean
     * @param arg
     * @throws Exception
     */
    public static void check(Object bean, String... arg) throws Exception {
        if (bean == null) {
            throw new GatewayException(GatewayErrorCodeEnum.INPUT_MUST_NOT_NULL.getCode(), "Object为空");
        }
        Class<?> type = bean.getClass();
        BeanInfo beanInfo = Introspector.getBeanInfo(type);
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (int i = 0; i < propertyDescriptors.length; i++) {
            PropertyDescriptor descriptor = propertyDescriptors[i];
            String propertyName = descriptor.getName();
            Method readMethod = descriptor.getReadMethod();
            Object result = readMethod.invoke(bean, new Object[0]);
            for (String attribute : arg) {
                if (attribute.equals(propertyName) && result == null) {
                    throw new GatewayException(GatewayErrorCodeEnum.INPUT_MUST_NOT_NULL.getCode(), "必传参数" + attribute
                            + "为空", attribute);
                }
            }
        }
    }

}
